import asyncio
import uuid

import aiohttp
import tornado.web
import tornado.ioloop
import tornado.httpserver
import tornado.httpclient
import os
import sys
import threading

pro_path = os.path.dirname(os.path.realpath(__file__))
root_path = os.path.dirname(os.path.dirname(os.path.dirname(pro_path)))
sys.path.append(pro_path)
sys.path.append(root_path)

from bot.insurance_planner_gpt.qw_server.access_token_manager import token_manager
from bot.insurance_planner_gpt.qw_server.common import wework_constants
from bot.insurance_planner_gpt.qw_server.wework_process_handler import WeWorkProcessHandler
from bot.insurance_planner_gpt.config.conf import profile_
from common.log import logger
import settings
from bot.insurance_planner_gpt.qw_server.utils import common_util
from bot.insurance_planner_gpt.wechat_sop_server import get_sop_send_msg

# 设置 SSL 配置
ssl_options = {
    "certfile": '../../../common/ssl/socket.chatlingxi.com.pem',
    "keyfile": '../../../common/ssl/socket.chatlingxi.com.key',
}


async def init():
    for wework_config in common_util.wework_config_list:
        # 加载配置启用的api_key 获取token存入到内存
        company_id = wework_config.get("COMPANY_ID")
        token = await token_manager.get_access_token_by_company_id(company_id)
        # 加微机器人跟圈量同步下  清除redis 重新加载进redis
        await get_all_robot(company_id, token)


def start_sop_send():
    asyncio.run(get_sop_send_msg())


async def get_all_robot(company_id, token):
    """获取机器人列表"""
    response_json = {}
    try:
        payload = {
            "uniq_sn": str(uuid.uuid4()).replace("-", "")
        }
        headers = {'Content-Type': 'application/json', 'Token': token}
        async with aiohttp.ClientSession() as session:
            async with session.post(wework_constants.WEWORK_INTERFACE_GET_ROBOT_LIST, json=payload,
                                    headers=headers) as response:
                data = await response.json()
                if response.status == 200 and data.get("errcode") == 0:
                    response_json['message'] = "请求成功"
                else:
                    response_json['message'] = data.get("err_msg")
    except Exception:
        response_json['message'] = "请求异常"
    logger.info(f"系统初始化，{company_id},同步机器人列表 请求结果:{response_json}")
    return response_json


if __name__ == '__main__':
    _routes = [
        (r"/wework/(.*)", WeWorkProcessHandler),
    ]
    app = tornado.web.Application(handlers=_routes, debug=False)
    if settings.ONLINE:
        http_server = tornado.httpserver.HTTPServer(app, ssl_options=ssl_options)
    else:
        http_server = tornado.httpserver.HTTPServer(app)
    port = profile_['wework_server']['port']
    http_server.bind(port)
    logger.info(f"********** wework server started on port:{port} **********")
    process_num = profile_['wework_server']['process_num']
    http_server.start(process_num)
    # 项目启动时进行初始化一次
    asyncio.get_event_loop().run_until_complete(init())
    threading.Thread(target=start_sop_send, args=()).start()
    tornado.ioloop.IOLoop.current().start()
